package com.xujianlun.cpms.controller.shop;


import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xujianlun.cpms.config.AuthAccess;
import com.xujianlun.cpms.dto.OrderGoodsDto;
import com.xujianlun.cpms.entity.shop.Carts;
import com.xujianlun.cpms.entity.shop.Goods;
import com.xujianlun.cpms.entity.shop.OrderGoods;
import com.xujianlun.cpms.entity.shop.Orders;
import com.xujianlun.cpms.entity.sys.User;
import com.xujianlun.cpms.mapper.shop.OrdersMapper;
import com.xujianlun.cpms.service.shop.ICartsService;
import com.xujianlun.cpms.service.shop.IGoodsService;
import com.xujianlun.cpms.service.shop.IOrderGoodsService;
import com.xujianlun.cpms.service.shop.IOrdersService;
import com.xujianlun.cpms.service.sys.IUserService;
import com.xujianlun.cpms.utils.TokenUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xujianlun.cpms.common.Response;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 订单表（业务数据） 前端控制器
 * </p>
 *
 * @author xujianlun
 * @since 2022-12-15
 */
@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Resource
    private IOrdersService ordersService;
    @Resource
    private IOrderGoodsService orderGoodsService;
    @Resource
    private ICartsService cartsService;
    @Resource
    private IUserService userService;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private OrdersMapper ordersMapper;
    // 新增或者更新
    @PostMapping
    public Response save(@RequestBody Orders orders) {
        if (orders.getId()==null){
            Integer userId = TokenUtil.getTokenUserId();
            User user = userService.getById(userId);
            Date date = new Date();
            orders.setCreateTime(DateUtil.formatDateTime(date));//设置当前时间
            orders.setNo(DateUtil.format(date,"yyyyMMdd") + System.currentTimeMillis());//时间作为订单编号
            orders.setUserId(userId);
            orders.setCard(user.getIdCard());
            orders.setPhone(user.getPhone());
            orders.setAddress(user.getAddress());
            orders.setDeliverGoods("未审核");
            //先创建订单
            ordersService.save(orders);
            //获取到购物车的对象直接绑定一下
            List<Carts> carts = orders.getCarts();
            for (Carts cart : carts){
                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setGoodsId(cart.getGoodsId());
                orderGoods.setNum(cart.getNum());
                orderGoods.setOrderId(orders.getId());
                orderGoodsService.save(orderGoods);
                //循环删除购物车的数据
                cartsService.removeById(cart.getId());
            }
        }else {
            ordersService.updateById(orders);
        }
        return Response.success();
    }

    @DeleteMapping("/{id}")
    public Response delete(@PathVariable Integer id) {
        ordersService.removeById(id);
        return Response.success();
    }

    @PostMapping("/del/batch")
    public Response deleteBatch(@RequestBody List<Integer> ids) {
        ordersService.removeByIds(ids);
        return Response.success();
    }

    @GetMapping
    public Response findAll() {
        return Response.success(ordersService.list());
    }

    @GetMapping("/{id}")
    public Response findOne(@PathVariable Integer id) {
        return Response.success(ordersService.getById(id));
    }


    @GetMapping("/page")
    public Response findPage(@RequestParam Integer pageNum,
                             @RequestParam Integer pageSize,
                             @RequestParam(defaultValue = "") String name,
                             @RequestParam(defaultValue = "") String phone,
                             @RequestParam(defaultValue = "") String no) {
//        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
//        queryWrapper.orderByDesc("id");
//        if (!"".equals(name)){
//            queryWrapper.like("name",name);
//        }
        //根据用户去查询
        Integer tokenUserId = TokenUtil.getTokenUserId();
        User user = userService.getById(tokenUserId);
        String role = user.getRole();
        return Response.success(ordersMapper.page(new Page<>(pageNum, pageSize), name,no,phone,role,tokenUserId));
    }

    /**
     * 订单详情数据，根据订单表ID查询订单-物品表
     * @param id
     * @return
     */
    @GetMapping("/getGoodsById/{id}")
    public Response findGoodsById(@PathVariable Integer id) {
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper  = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("order_id",id);
        List<OrderGoods> orderGoodsList = orderGoodsService.list(orderGoodsQueryWrapper);
        ArrayList<Goods> goodsArrayList = new ArrayList<>();
        for (OrderGoods orderGoods : orderGoodsList){
            Integer goodsId = orderGoods.getGoodsId();
            Goods goods = goodsService.getById(goodsId);
            //获取商品的数量
            goods.setNum(orderGoods.getNum());
            goodsArrayList.add(goods);

        }
        return Response.success(goodsArrayList);
    }
    //修改发货状态
    @PostMapping("/devGoods")
    public Response update(@RequestBody Orders orders) {
        ordersMapper.updateById(orders);
        return Response.success();
    }

    /**
     * 生成发货Excel列表
     */
    @AuthAccess
    @GetMapping("/export/ByIds")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
//        List<User> list = userService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");

        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        ordersQueryWrapper.eq("deliver_Goods","已审核");
        List<Orders> ordersList = ordersService.list(ordersQueryWrapper);
        ArrayList<OrderGoodsDto> orderGoodsDtoArrayList = new ArrayList<>();
        for (Orders orders : ordersList){
            User user = userService.getById(orders.getUserId());
            QueryWrapper<OrderGoods> orderGoodsQueryWrapper  = new QueryWrapper<>();
            orderGoodsQueryWrapper.eq("order_id",orders.getId());
            List<OrderGoods> orderGoodsList = orderGoodsService.list(orderGoodsQueryWrapper);
            ArrayList<Goods> goodsArrayList = new ArrayList<>();
            for (OrderGoods orderGoods : orderGoodsList){
                Integer goodsId = orderGoods.getGoodsId();
                Goods goods = goodsService.getById(goodsId);
                //获取商品的数量
                goods.setNum(orderGoods.getNum());
                goodsArrayList.add(goods);
            }
            OrderGoodsDto orderGoodsDto = new OrderGoodsDto();
            orderGoodsDto.setNo(orders.getNo());//订单号
            orderGoodsDto.setName(orders.getName());//订单名
            orderGoodsDto.setPhone(orders.getPhone());//联系人手机号
            orderGoodsDto.setNickName(user.getNickName());//收货人的姓名
            orderGoodsDto.setAmount(orders.getSumPrice());//总的价格
            orderGoodsDto.setAddress(orders.getAddress());//收货地址
            ArrayList arrayList = new ArrayList();
            for (Goods goods:goodsArrayList){
               arrayList.add(goods.getName());
               arrayList.add("单价"+goods.getPrice()+"元");
               arrayList.add(goods.getNum()+goods.getUnit());
            }
            orderGoodsDto.setGoodsList(arrayList);//显示商品名称
            orderGoodsDtoArrayList.add(orderGoodsDto);
            orders.setDeliverGoods("已发货");
            ordersService.updateById(orders);
        }
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("no", "订单编号");
        writer.addHeaderAlias("name", "订单名");
        writer.addHeaderAlias("goodsList", "购买的商品");
        writer.addHeaderAlias("amount", "订单总价格");
        writer.addHeaderAlias("phone", "收货人手机号");
        writer.addHeaderAlias("nickName", "姓名");
        writer.addHeaderAlias("address", "地址");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(orderGoodsDtoArrayList, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("发货信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }
}

